<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId">
        <el-form-item label="登录账号" prop="loginName">
          <el-input
            placeholder="请输入登录账号"
            v-model="searchParams.loginName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            placeholder="请输入用户名称"
            v-model="searchParams.userName"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            placeholder="请输入手机号"
            v-model="searchParams.phone"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <!-- 部门级联选择框 -->
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            placeholder="请选择部门"
            v-model="searchParams.deptId"
            :options="cascaderOptions"
            :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
            filterable
            clearable
            style="width: 260px"
          >
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="登录时间" prop="loginTime">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            range-separator="至"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch()" v-auth="['system:user:search']">搜索</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:user:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:role']">
          <el-button type="primary" icon="edit" plain @click="handleAssignRoles()" :disabled="single">分配角色</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:post']">
          <el-button type="success" icon="edit" plain @click="handleAssignPosts()" :disabled="single">分配岗位</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:export']">
          <el-button type="warning" icon="download" plain @click="handleExportExcel(searchParams)">导出</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:user:import']">
          <el-button type="info" icon="upload" plain @click="handleImportExcel()">导入</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 :data="tableList" -->
      <!-- 静态数据表格分页 :data="tableList.slice((searchParams.pageNo - 1) * searchParams.pageSize, searchParams.pageNo * searchParams.pageSize)" -->
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟🌻"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="userId" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="登录账号"
          prop="loginName"
          width="150px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="部门名称"
          prop="deptName"
          width="180px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="头像" prop="avatar" width="80px" align="center">
          <template #default="scope">
            <div class="flex justify-center">
              <el-image
                class="rounded-full w-36px h-36px"
                :preview-teleported="true"
                :preview-src-list="[scope.row.avatar]"
                :src="
                  scope.row.avatar != null && scope.row.avatar != ''
                    ? scope.row.avatar
                    : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                "
              >
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="用户名称"
          prop="userName"
          width="120px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="邮箱" prop="email" width="220px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="手机号" prop="phone" width="130px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="用户类型" prop="userType" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_user_type" :value="scope.row.userType"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="用户性别" prop="sex" width="90px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_user_sex" :value="scope.row.sex"></KoiTag>
          </template>
        </el-table-column>
        <!-- 注意：如果后端数据返回的是字符串"0" OR "1",这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
        <el-table-column label="用户状态" prop="userStatus" width="90px" align="center">
          <template #default="scope">
            <!-- {{ scope.row.userStatus }} -->
            <el-switch
              v-model="scope.row.userStatus"
              active-text="启用"
              inactive-text="停用"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="登录时间" prop="loginTime" width="180px" align="center"></el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
          fixed="right"
          v-auth="['system:user:update', 'system:user:delete', 'system:user:resetPwd']"
        >
          <template #default="{ row }">
            <el-tooltip content="修改🌻" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:user:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除🌻" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:user:delete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="重置密码🌻" placement="top">
              <el-button
                type="warning"
                icon="Key"
                circle
                plain
                @click="handleResetPwd(row)"
                v-auth="['system:user:resetPwd']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- {{ searchParams.pageNo }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="登录账号" prop="loginName">
                  <el-input v-model="form.loginName" placeholder="请输入登录账号" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" v-if="showPwd">
                <el-form-item label="登录密码" prop="password">
                  <el-input type="password" v-model="form.password" show-password placeholder="请输入登录账号" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户名称" prop="userName">
                  <el-input v-model="form.userName" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <!-- 部门级联选择框 -->
                <el-form-item label="部门名称" prop="deptId">
                  <el-cascader
                    placeholder="请选择部门"
                    v-model="form.deptId"
                    :options="cascaderOptions"
                    :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
                    filterable
                    clearable
                  >
                    <template #default="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" v-auth="['system:user:post']">
                <el-form-item label="分配岗位" prop="postId">
                  <el-select v-model="form.postIds" multiple placeholder="请选择岗位">
                    <el-option v-for="item in postOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" v-auth="['system:user:role']">
                <el-form-item label="分配角色" prop="roleId">
                  <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                    <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户类型" prop="userType">
                  <el-select placeholder="请选择用户类型" v-model="form.userType" clearable>
                    <el-option
                      v-for="item in koiDicts.sys_user_type"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户状态" prop="userStatus">
                  <el-select v-model="form.userStatus" placeholder="请选择用户状态" clearable>
                    <el-option label="启用" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户性别" prop="sex">
                  <el-radio-group v-model="form.sex" placeholder="请选择性别">
                    <el-radio label="1" border>男</el-radio>
                    <el-radio label="2" border>女</el-radio>
                    <el-radio label="3" border>未知</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户头像" prop="avatar">
                  <KoiUploadImage v-model:imageUrl="form.avatar">
                    <template #content>
                      <el-icon><Avatar /></el-icon>
                      <span>请上传头像</span>
                    </template>
                    <template #tip>图片最大为 3M</template>
                  </KoiUploadImage>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入用户备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- {{ form }} -->
        </template>
      </KoiDrawer>

      <KoiDialog ref="koiRoleDialogRef" title="分配角色" :height="450" :footerHidden="true">
        <template #content>
          <div class="flex flex-justify-center">
            <el-transfer
              :props="{
                key: 'value',
                label: 'label'
              }"
              :titles="['角色列表', '拥有角色']"
              target-order="original"
              filterable
              filter-placeholder="关键字搜索"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              v-model="transferRightRoleList"
              :data="transferLeftRoleList"
              @change="handleRoleTransferChange"
            />
          </div>
        </template>
      </KoiDialog>

      <KoiDialog ref="koiPostDialogRef" title="分配岗位" :height="450" :footerHidden="true">
        <template #content>
          <div class="flex flex-justify-center">
            <el-transfer
              :props="{
                key: 'value',
                label: 'label'
              }"
              :titles="['岗位列表', '分配岗位']"
              target-order="original"
              filterable
              filter-placeholder="关键字搜索"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              v-model="transferRightPostList"
              :data="transferLeftPostList"
              @change="handlePostTransferChange"
            />
          </div>
        </template>
      </KoiDialog>

      <KoiExcel ref="koiExcelRef" @handleTemplateExcel="handleTemplateExcel"></KoiExcel>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="userPage">
import { ref, reactive, onMounted } from "vue";
import {
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgInfo,
  koiMsgSuccess,
  koiMsgWarning,
  koiMsgError,
  koiMsgBox,
  koiMsgBoxPrompt
} from "@/utils/koi.ts";
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus, resetPwd, exportData, downloadTemplate } from "@/api/system/user/index.ts";
import { listNormalRole, assignUserRole, listRoleElSelect } from "@/api/system/role/index.ts";
import { listNormalPost, assignUserPost, listPostElSelect } from "@/api/system/post/index.ts";
import { handleTree } from "@/utils/index.ts";
import { cascaderList } from "@/api/system/dept/index.ts";
import { koiDatePicker } from "@/utils/index.ts";
import { useKoiDict } from "@/hooks/dicts/index.ts";
const { koiDicts } = useKoiDict(["sys_user_type", "sys_user_sex"]);

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 时间
const dateRange = ref();

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  loginName: "",
  userName: "",
  phone: "",
  deptId: ""
});
const total = ref<number>(0);
// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    loginName: "",
    userName: "",
    phone: "",
    deptId: ""
  };
  dateRange.value = [];
};

// 级联下拉框
const cascaderOptions = ref<any>([]);
/** 部门级联数据 */
const handleCascader = async () => {
  try {
    cascaderOptions.value = [];
    const res: any = await cascaderList();
    cascaderOptions.value = handleTree(res.data, "value");
  } catch (error) {
    console.log(error);
    koiMsgError("部门级联数据查询失败，请重试🌻");
  }
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
    console.log("用户数据表格数据->", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
    // console.log("用户数据表格数据->", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
  handleCascader();
});

const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.userId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 岗位下拉框
const postOptions = ref<any>([]);
// 角色下拉框
const roleOptions = ref<any>([]);
// 添加显示密码框，修改隐藏密码框
const showPwd = ref(true);

// 岗位下拉框
const listPostOptions = async () => {
  try {
    const res: any = await listPostElSelect();
    postOptions.value = res.data;
  } catch (error) {
    koiMsgError("岗位信息加载失败🌻");
    console.log(error);
  }
};

// 角色下拉框
const listRoleOptions = async () => {
  try {
    const res: any = await listRoleElSelect();
    roleOptions.value = res.data;
  } catch (error) {
    koiMsgError("角色信息加载失败🌻");
    console.log(error);
  }
};

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 显示密码框
  showPwd.value = true;
  // 岗位下拉框
  listPostOptions();
  // 角色下拉框
  listRoleOptions();
  // 标题
  title.value = "用户添加";
  form.value.userStatus = "0";
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("添加🌻");
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  console.log("回显数据ID", id);
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据🌻");
    return;
  }
  try {
    const res: any = await getById(id);
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试🌻");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 隐藏密码框
  showPwd.value = false;
  // 标题
  title.value = "用户修改";
  const userId = row ? row.userId : ids.value[0];
  if (userId == null || userId == "") {
    koiMsgError("请选中需要修改的数据🌻");
  }
  console.log(userId);
  // 回显数据
  handleEcho(userId);
  // 岗位下拉框
  listPostOptions();
  // 角色下拉框
  listRoleOptions();
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("修改🌻");
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  loginName: null,
  password: "123456",
  userName: null,
  deptId: null,
  postIds: [],
  roleIds: [],
  userType: "1",
  userStatus: "0",
  sex: "3",
  avatar: null,
  phone: null,
  remark: null
});
/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    loginName: null,
    password: "123456",
    userName: null,
    userType: "1",
    userStatus: "0",
    sex: "3",
    avatar: null,
    phone: null,
    email: null,
    remark: null
  };
  postOptions.value = [];
  roleOptions.value = [];
};
/** 表单规则 */
const rules = reactive({
  loginName: [{ required: true, message: "请输入用户名字", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
  userName: [{ required: true, message: "请输入用户名字", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择用户部门", trigger: "blur" }],
  userType: [{ required: true, message: "请输入用户类型", trigger: "blur" }],
  sex: [{ required: true, message: "请选择用户性别", trigger: "blur" }],
  userStatus: [{ required: true, message: "请输入选择用户状态", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  if (form.value.postIds.length === 0) {
    form.value.postIds = [-1];
  }
  if (form.value.roleIds.length === 0) {
    form.value.roleIds = [-1];
  }
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      console.log("表单ID", form.value.userId);
      if (form.value.userId != null && form.value.userId != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试🌻");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功🌻");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试🌻");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容🌻");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 状态switch */
const handleSwitch = (row: any) => {
  let text = row.userStatus === "0" ? "启用" : "停用";
  koiMsgBox("确认要[" + text + "]-[" + row.userName + "]吗？")
    .then(async () => {
      resetForm();
      if (!row.userId || !row.userStatus) {
        koiMsgWarning("请选择需要修改的数据🌻");
        return;
      }
      try {
        await updateStatus(row.userId, row.userStatus);
        koiNoticeSuccess("修改成功🌻");
      } catch (error) {
        console.log(error);
        koiNoticeError("修改失败，请刷新重试🌻");
        handleTableData();
      }
    })
    .catch(() => {
      row.userStatus = row.userStatus == "0" ? "1" : "0";
      koiMsgError("已取消🌻");
    });
};

/** 分配角色 */
// 分配角色弹出框
const koiRoleDialogRef = ref();
// 左侧所有数据
const transferLeftRoleList = ref<any>([]);
// 右侧选中数据
const transferRightRoleList = ref<any>([]);
const handleAssignRoles = async () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请先选择数据🌻");
    return;
  }
  try {
    // 传递当前登录用户ID
    const res: any = await listNormalRole(ids.value[0]);
    transferLeftRoleList.value = res.data.data1; // 左侧所有数据，右边出现一样的会自动进行去除
    transferRightRoleList.value = res.data.data2;
  } catch (error) {
    console.log(error);
    koiMsgError("加载角色数据失败");
  }
  koiRoleDialogRef.value.koiOpen();
};

// 右侧列表元素变化时触发
const handleRoleTransferChange = async (value: any) => {
  if (ids.value.length == 0) {
    koiMsgInfo("请先选择数据🌻");
    return;
  }
  console.log(value);
  try {
    await assignUserRole(ids.value[0], value);
    koiNoticeSuccess("分配角色成功🌻");
  } catch (error) {
    console.log(error);
    handleAssignRoles();
    koiMsgError("分配角色失败，请重试");
  }
};

/** 分配岗位 */
// 分配岗位弹出框
const koiPostDialogRef = ref();
// 左侧所有数据
const transferLeftPostList = ref<any>([]);
// 右侧选中数据
const transferRightPostList = ref<any>([]);
const handleAssignPosts = async () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请先选择数据🌻");
    return;
  }
  try {
    // 传递当前登录用户ID
    const res: any = await listNormalPost(ids.value[0]);
    transferLeftPostList.value = res.data.data1; // 左侧所有数据，右边出现一样的会自动进行去除
    transferRightPostList.value = res.data.data2;
  } catch (error) {
    console.log(error);
    koiMsgError("加载岗位数据失败");
  }
  koiPostDialogRef.value.koiOpen();
};

// 右侧列表元素变化时触发
const handlePostTransferChange = async (value: any) => {
  if (ids.value.length == 0) {
    koiMsgInfo("请先选择数据🌻");
    return;
  }
  try {
    await assignUserPost(ids.value[0], value);
    koiNoticeSuccess("分配岗位成功🌻");
  } catch (error) {
    console.log(error);
    handleAssignPosts();
    koiMsgError("分配岗位失败，请重试");
  }
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.userId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据🌻");
  }
  koiMsgBox("您确认需要删除用户名称[" + row.userName + "]么？")
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiNoticeSuccess("删除成功🌻");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("删除失败，请刷新重试🌻");
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据🌻");
    return;
  }
  koiMsgBox("您确认需要进行批量删除么？")
    .then(async () => {
      try {
        console.log("ids", ids.value);
        await batchDelete(ids.value);
        handleTableData();
        koiNoticeSuccess("批量删除成功🌻");
      } catch (error) {
        console.log(error);
        koiNoticeError("批量删除失败，请刷新重试🌻");
        handleTableData();
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};

/** 重置密码 */
const handleResetPwd = (row: any) => {
  const id = row.userId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要重置密码的数据🌻");
  }
  koiMsgBoxPrompt()
    .then(async (res: any) => {
      if (res.value == null || res.value == "") {
        koiMsgWarning("用户密码不能为空🌻");
        return;
      }
      if (res.value.length < 6) {
        koiMsgWarning("密码长度不能小于6位🌻");
        return;
      }
      await resetPwd(id, res.value);
      koiMsgSuccess("重置密码成功🌻");
    })
    .catch((error: any) => {
      koiMsgError(error + "🌻");
    });
};

/** 数据导出 */
const handleExportExcel = async (params: any) => {
  console.log("params:", params)
  try {
    const res: any = await exportData(params);
    const objectUrl = URL.createObjectURL(
      new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })
    );
    const link = document.createElement('a');
    // 设置导出的文件名称
    link.download = "导出数据.xlsx";
    link.style.display = 'none';
    link.href = objectUrl;
    link.click();
    document.body.appendChild(link);
  } catch (error) {
      console.error(error);
      koiNoticeError("导出失败🌻");
  }
}

/** Excel组件 */
const koiExcelRef = ref();
/** 下载模板 */
const handleTemplateExcel = async () => {
  try {
    const res: any = await downloadTemplate();
    const objectUrl = URL.createObjectURL(
      new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })
    );
    const link = document.createElement('a');
    // 设置导出的文件名称
    link.download = "下载模版.xlsx";
    link.style.display = 'none';
    link.href = objectUrl;
    link.click();
    document.body.appendChild(link);
  } catch (error) {
    console.error(error);
    koiNoticeError("下载模版失败🌻")
  }
};

/** 数据导入 */
const handleImportExcel = () => {
  let params = {
    title: "导入数据",
    importApi: import.meta.env.VITE_SERVER + "/koi/sysLoginUser/importExcelData"
  };
  koiExcelRef.value.excelParams(params);
};
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>
